<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 图片列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd" style="margin-right: 10px"
        >上传图片
        </el-button
        >
        <el-input v-model="query.name" placeholder="图片名称" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </div>
      <el-table :data="tableData" border class="table" height="360" header-cell-class-name="table-header">
        <el-table-column prop="fileName" label="图片名称"></el-table-column>
        <el-table-column prop="des" label="图片描述"></el-table-column>
        <el-table-column prop="fileFullPath" label="图片地址" sortable></el-table-column>
        <el-table-column prop="tag" label="一级类别"></el-table-column>
        <el-table-column prop="secondaryTag" label="二级类别"></el-table-column>
        <el-table-column label="图片详情(查看大图)" align="center">
          <template slot-scope="scope">
            <el-image
              class="table-td-thumb"
              :src="scope.row.fileFullPath"
              :preview-src-list="[scope.row.fileFullPath]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="图片名称">
          <el-input v-model="form.fileName"></el-input>
        </el-form-item>
        <el-form-item label="图片简介">
          <el-input v-model="form.brief"></el-input>
        </el-form-item>
        <el-form-item label="图片描述">
          <el-input type="textarea" v-model="form.des"></el-input>
        </el-form-item>
        <el-form-item label="图片地址">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload class="avatar-uploader" action="#" :show-file-list="true" :on-success="handleEditAvatarSuccess">
            <img v-if="form.cover != ''" :src="form.cover" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="30%">
      <el-form label-width="70px">
        <el-form-item label="图片名称">
          <el-input v-model="fileName"></el-input>
        </el-form-item>
        <el-form-item label="图片描述">
          <el-input type="textarea" v-model="des"></el-input>
        </el-form-item>
        <el-form-item label="一级分类">
          <el-input v-model="tag"></el-input>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-input v-model="secondaryTag"></el-input>
        </el-form-item>
        <el-form-item label="封面图">
          <input name="file" type="file" accept="*" @change="uploadFile"/>
          <div class="upload">
            <i class="el-icon-plus" v-show="imgShow == 0"></i>
            <img src="" alt="" id="uploadImg" v-show="imgShow == 1"/>
            <!-- <video v-else-if="imgShow == 2" width="100%" height="100%" id="uploadVideo" muted loop="loop" autoplay="autoplay">
                <source id="v1" src="" />
            </video> -->
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd()">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadPicture, getPicture, deletePicture } from '@/api/file'

export default {
  name: 'File',
  data() {
    return {
      query: {
        address: 'goods',
        name: '',
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [
        {
          fileName: '',
          des: '',
          tag: '',
          secondaryTag: '',
          fileFullPath: ''
        }
      ],
      editVisible: false,
      addVisible: false,
      file: {},
      fileName: '',
      tag: '',
      secondaryTag: '',
      brief: '',
      des: '',
      address: '',
      pageTotal: 0,
      form: {},
      idx: -1,
      id: -1,
      imgShow: 0,
      imageUrl: '' //upload的图片地址
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    // 获取 easy-mock 的模拟数据
    async getData() {
      const res = await getPicture()
      this.tableData = res.data.records
      this.query = res.data
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, 'pageIndex', 1)
      this.getData()
    },
    // 删除操作
    handleDelete(id) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          deletePicture(id).then((res) => {
            console.log(res)
            this.$message.success('删除图片成功！')
            this.getData()
          })
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // edit upload函数
    handleEditAvatarSuccess(res, file) {
      //this.imageUrl = URL.createObjectURL(file.raw);
      if (res.status == 1) {
        this.form.cover = res.image_path
      } else {
        this.$message.error('上传图片失败！')
      }
    },
    uploadFile(e) {
      this.file = e.target.files[0]
      if (this.file) {
        // if (isAssetTypeAnImage(this.file)) {
        console.log(this.file)
        this.imgShow = 1
        var url = URL.createObjectURL(this.file)
        document.getElementById('uploadImg').src = url
        // }
        // } else {
        //     this.imgShow = 2;
        //     var url = URL.createObjectURL(this.file.name);
        //     document.getElementById('v1').src = url;
        //     document.getElementById('uploadVideo').load();
        // }
      }
    },
    // 保存新增
    async saveAdd() {
      let formdata = new FormData()
      formdata.append('file', this.file)
      formdata.append('des', this.des)
      formdata.append('fileName', this.fileName)
      formdata.append('tag', this.tag)
      formdata.append('secondaryTag', this.secondaryTag)
      const res = await uploadPicture(formdata)
      if (res.status === '00000') {
        this.$message({
          showClose: true,
          message: '上传图片成功！',
          type: 'success'
        })
        this.addVisible = false
        this.file = {}
        this.getData()
      } else {
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index
      this.form = row
      this.editVisible = true
    },
    // 保存编辑
    saveEdit() {
      // 判断空值
      var isEmpty = false
      for (let [key, value] of Object.entries(this.form)) {
        console.log(value)
        if (value == null || value == '') {
          isEmpty = true
          break
        }
      }

      if (isEmpty) {
        this.$message.error(`请将每一项填写完整`)
      } else {
        this.editVisible = false
        this.$message.success(`修改成功`)
        this.$set(this.tableData, this.idx, this.form)
      }
    },
    // add upload函数
    handleAddAvatarSuccess(res, file) {
      //this.imageUrl = URL.createObjectURL(file.raw);
      if (res.status == 1) {
        this.imageUrl = res.image_path
        console.log(this.imageUrl)
      } else {
        this.$message.error('上传图片失败！')
      }
    },
    // 新增操作
    handleAdd() {
      this.file = ''
      this.fileName = ''
      this.des = ''
      this.tag = ''
      this.secondaryTag = ''
      this.addVisible = true
      this.imgShow = 0
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'pageIndex', val)
      this.getData()
    }
  }
}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 100px;
  height: 80px;
}

.upload {
  width: 160px;
  height: 92px;
  border: 1px dashed lightgray;
  text-align: center;
  font-size: 24px;
  line-height: 92px;
}

.upload > img {
  width: 100%;
  height: 100%;
}
</style>
